import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/models/me.dart';
import 'package:fsharing/core/models/user_invited.dart';
import 'package:fsharing/core/viewmodels/pages/mine/user_invited_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/main.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class InvitedPageArgs {
  final Me me;
  final int currentUserId;
  final int targetUserId;

  InvitedPageArgs(this.me, this.currentUserId, this.targetUserId);
}

class InvitedPage extends StatelessWidget {
  final InvitedPageArgs args;

  InvitedPage({
    Key key,
    @required this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => UserInvitedModel(
        Provider.of(context, listen: false),
        args.me,
        args.currentUserId,
        args.targetUserId,
      ),
      child: BackgroundContainer(
        child: Consumer<UserInvitedModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: CircularProgressIndicator(),
                  ),
                );
              case ViewState.error:
                return Scaffold(
                  appBar: child,
                  body: Center(
                    child: Text(model.errorMessage),
                  ),
                );
              case ViewState.success:
                return Scaffold(
                  appBar: AppBar(
                    leading: RoundBackButton(),
                    title: Text('${model.userInvited.targetUser.username}邀请的好友'),
                    actions: <Widget>[
                      _QrcodeActionWidget(),
                    ],
                  ),
                  body: _BodyWidget(),
                );
              default:
                return Container();
            }
          },
          child: AppBar(
            leading: RoundBackButton(),
            title: Text('邀请的好友'),
          ),
        ),
      ),
    );
  }
}

class _QrcodeActionWidget extends StatelessWidget {
  const _QrcodeActionWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 4),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(
              'assets/images/user/ic_qr_code.png',
              width: 16,
              height: 16,
              color: Colors.white,
            ),
            Container(
              margin: EdgeInsets.only(top: 4),
              child: Text(
                '我的二维码',
                style: TextStyle(color: Colors.white, fontSize: 9),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        _onQrcodeClicked(context);
      },
    );
  }

  void _onQrcodeClicked(BuildContext context) {
    UserInvitedModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed('/invite', arguments: model.me);
  }
}

class _BodyWidget extends StatelessWidget {
  final RefreshController _refreshController = RefreshController();

  @override
  Widget build(BuildContext context) {
    UserInvitedModel model = Provider.of(context, listen: false);
    List<User> list = model.list;
    List<User> invitedUsers = model.userInvited.invitedUsers;
    return SmartRefresher(
      controller: _refreshController,
      child: CustomScrollView(
        slivers: <Widget>[
          SliverPadding(
            padding: EdgeInsets.symmetric(horizontal: 12),
            sliver: SliverToBoxAdapter(
              child: _HeaderWidget(),
            ),
          ),
          SliverPadding(
            padding: EdgeInsets.symmetric(horizontal: 12),
            sliver: SliverList(
              delegate: SliverChildBuilderDelegate(
                (context, index) {
                  User user = list[index];
                  return _ListItemWidget(
                    isLast: index == list.length - 1,
                    user: user,
                  );
                },
                childCount: list.length,
              ),
            ),
          ),
        ],
      ),
      enablePullDown: false,
      enablePullUp: invitedUsers.length == 10,
      onLoading: () {
        _onLoadData(context);
      },
    );
  }

  void _onLoadData(BuildContext context) async {
    UserInvitedModel model = Provider.of(context, listen: false);
    await model.loadData();
    _refreshController.loadComplete();
  }
}

class _HeaderWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserInvitedModel model = Provider.of(context, listen: false);
    final targetUser = model.userInvited.targetUser;
    return Container(
      padding: EdgeInsets.all(8),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/user/img_header.png'),
          fit: BoxFit.fill,
        ),
      ),
      // height: 85,
      child: Column(
        children: <Widget>[
          Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  '邀请人数',
                  style: TextStyle(fontSize: 17),
                ),
              ),
              Text.rich(
                TextSpan(
                  text: '${targetUser.invitedCount}',
                  style: TextStyle(color: Theme.of(context).accentColor, fontSize: 17),
                  children: [
                    TextSpan(
                      text: '人',
                      style: TextStyle(color: Colors.white),
                    )
                  ],
                ),
              ),
            ],
          ),
          Divider(),
          Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  targetUser.storeInfo,
                  style: TextStyle(color: Colors.grey),
                ),
              ),
              Container(
                width: 70,
                height: 27,
                child: RaisedButton(
                  onPressed: () {
                    _onRenewClicked(context);
                  },
                  padding: EdgeInsets.zero,
                  child: Text('续费详情'),
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  void _onRenewClicked(BuildContext context) {
    UserInvitedModel model = Provider.of(context, listen: false);
    final userId = model.userInvited.targetUser.id;
    Navigator.of(context).pushNamed('/renew', arguments: userId);
  }
}

class _ListItemWidget extends StatelessWidget {
  final bool isLast;
  final User user;

  const _ListItemWidget({
    Key key,
    @required this.isLast,
    @required this.user,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Theme(
      data: lightTheme(),
      child: Material(
        borderRadius: isLast
            ? BorderRadius.vertical(
                bottom: Radius.circular(8),
              )
            : BorderRadius.zero,
        child: InkWell(
          child: Container(
            padding: EdgeInsets.all(8),
            height: 84,
            child: Row(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.circular(4),
                  child: CachedNetworkImage(
                    imageUrl: user.avatar ?? '',
                    width: 45,
                    height: 45,
                    fit: BoxFit.fill,
                  ),
                ),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(left: 8, top: 4),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Text(
                              '${user.username}',
                              style: TextStyle(fontSize: 15),
                            ),
                            Container(
                              margin: EdgeInsets.only(left: 8),
                              child: Container(
                                padding: EdgeInsets.symmetric(vertical: 2, horizontal: 4),
                                decoration: BoxDecoration(
                                  color: user.realName == null
                                      ? Colors.grey
                                      : Theme.of(context).accentColor,
                                  borderRadius: BorderRadius.circular(4),
                                ),
                                child: Text(
                                  user.realName == null ? '未实名' : '已认证',
                                  style: TextStyle(color: Colors.white, fontSize: 10),
                                ),
                              ),
                            )
                          ],
                        ),
                        Text(
                          '已邀请：${user.invitedCount}人',
                          style: TextStyle(color: Colors.grey, fontSize: 13),
                        ),
                        Text(
                          '创建时间：${user.createTime}',
                          style: TextStyle(color: Colors.grey, fontSize: 13),
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  width: 48,
                  height: 19,
                  child: RaisedButton(
                    onPressed: () {
                      _onRenewClicked(context);
                    },
                    padding: EdgeInsets.zero,
                    child: Text(
                      '续费详情',
                      style: TextStyle(fontSize: 10),
                    ),
                  ),
                ),
                Container(
                  child: Icon(
                    Icons.keyboard_arrow_right,
                    size: 16,
                    color: Colors.grey,
                  ),
                )
              ],
            ),
          ),
          onTap: () {
            _onItemClicked(context);
          },
        ),
      ),
    );
  }

  void _onRenewClicked(BuildContext context) {
    Navigator.of(context).pushNamed('/renew', arguments: user.id);
  }

  void _onItemClicked(BuildContext context) {
    UserInvitedModel model = Provider.of(context, listen: false);
    final me = model.me;
    final currentUserId = model.userInvited.targetUser.id;
    final targetUserId = user.id;
    Navigator.of(context).pushNamed(
      '/invited',
      arguments: InvitedPageArgs(me, currentUserId, targetUserId),
    );
  }
}
